<template>

  <div>
    <span class="titleStr">产品信息</span>
    <el-progress :percentage="100"  :show-text="false"></el-progress>
    <span class="describe">
    </span>
    <br>
    <el-form :model="productShow" :rules="rules"  label-width="100px"  ref="productForm">
      <el-form-item label="产品编码">
        <el-input  placeholder="自动生成无需添加" :disabled="true" style="width: 80%"></el-input>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="产品名称"  prop="productName">
            <el-input v-model="productShow.productName" placeholder="请输入产品名称" required></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="采购单价/元"  prop="productUnitPrice">
            <el-input
                v-model="productShow.productUnitPrice"
                placeholder="请输入采购单价"
                type="number"
                step="0.01"
                @input="formatPriceMoney"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item label="规格型号"  prop="productModels">
            <el-input v-model="productShow.productModels" placeholder="请输入规格型号"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="产品品牌"  prop="productBrand">
            <el-input v-model="productShow.productBrand" placeholder="请输入产品品牌" required></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="10">
          <el-form-item  label="产品属性"  prop="productAttribute">
            <el-select v-model="productShow.productAttribute" @change="handleProductAttributeChange">
              <el-option
                  v-for="productAttribute in productAttributes"
                  :key="'productAttribute'+productAttribute.dictCode"
                  :label="productAttribute.dictLabel"
                  :value="productAttribute.dictLabel"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="单位"  prop="priductUnit">
            <el-select v-model="productShow.priductUnit">
              <el-option
                  v-for="priductUnit in priductUnits"
                  :key="'priductUnit'+priductUnit.dictCode"
                  :label="priductUnit.dictLabel"
                  :value="priductUnit.dictCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="产品类型"  prop="productType">
            <el-select v-model="productShow.productType">
              <el-option
                  v-for="productType in productTypes"
                  :key="'productType'+productType.id"
                  :label="productType.productType"
                  :value="productType.productType"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item>
            <el-row>
              <el-form-item label="产品采购权限">
                <el-switch
                    v-model="productShow.purchasePermissions"
                    active-value="true"
                    active-color="yellow"
                    inactive-value="false"
                />
              </el-form-item>
              <el-form-item label="产品赠送权限">
                <el-switch
                    v-model="productShow.presentedPermissions"
                    active-value="true"
                    active-color="red"
                    inactive-value="false"
                />
              </el-form-item>
              <el-form-item label="产品销售权限">
                <el-switch
                    v-model="productShow.salePermissions"
                    active-value="true"
                    active-color="green"
                    inactive-value="false"
                />
              </el-form-item>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="10"  style="padding-left: 5%">
          <el-form-item label="添加产品图片">
          </el-form-item>
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/manage/product/uploadPic"
              :show-file-list="false"
              accept=".jpg,.jpeg,.png,.gif"
              :headers="headers"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-col>
      </el-row>
      <br>
      <el-form-item>
        <el-button type="primary" @click="submitForm">添加产品</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>

import productType from "@/router/productType";

export default {
  data() {
    return {
      productShow: {
        productName: '',
        productUnitPrice: '',
        productBrand:'',
        productAttribute: '',
        priductUnit:'',
        productImgsId:'',
        productModels:'',
        purchasePermissions: false,
        presentedPermissions: false,
        salePermissions: false,
        fileList: [],
      },
      headers:{token:window.localStorage.getItem("token")},
      imageUrl: '',
      productAttributes: [],
      priductUnits:[],
      productTypes:[],
      rules: {
        productName: [
          { required: true, message: '请输入产品名称', trigger: 'blur' }
        ],
        productUnitPrice: [
          { required: true, message: '请输入采购单价', trigger: 'blur' },

        ],
        productBrand: [
          { required: true, message: '请输入产品品牌', trigger: 'blur' }
        ],
        productAttribute: [
          { required: true, message: '请选择产品属性', trigger: 'change' }
        ],
        productType:[
          { required: true, message: '请选择产品类型', trigger: 'change' }
        ],
        priductUnit: [
          { required: true, message: '请选择单位', trigger: 'change' }
        ],
        productModels: [
          { required: true, message: '请输入规格型号', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.fetchDictDataByAttribute();
    this.fetchDictDataByUnit();
  },
  methods: {
    submitForm() {
      this.$refs.productForm.validate((valid) => {
        if (valid) {
          this.addProduct();
        } else {
          console.log('请输入内容');
          return false;
        }
      });
    },


    addProduct() {
      const productData = {
        productImgsId: this.productShow.productImgsId,
        productName: this.productShow.productName,
        productUnitPrice: this.productShow.productUnitPrice,
        productBrand: this.productShow.productBrand,
        productAttribute:this.productShow.productAttribute,
        priductUnit: this.productShow.priductUnit,
        productModels: this.productShow.productModels,
        purchasePermissions: this.productShow.purchasePermissions,
        presentedPermissions: this.productShow.presentedPermissions,
        salePermissions: this.productShow.salePermissions,
        productType: this.productShow.productType,
      };
      axios.post("http://localhost:8080/manage/product/add", productData)
          .then(response => {
            this.productShow.productName = '';
            this.productShow.productUnitPrice = '';
            this.productShow.productBrand = '';
            this.productShow.productAttribute = '';
            this.productShow.priductUnit = '';
            this.productShow.productModels = '';
            this.productShow.productImgsId = '';
            this.productShow.productType = '';
            this.productShow.purchasePermissions = false;
            this.productShow.presentedPermissions = false;
            this.productShow.salePermissions = false;


            this.$message.success('产品添加成功');
          })
          .catch(error => {
            this.$message.error('产品添加失败');
          })
    },
    formatPriceMoney(value){
      this.productShow.productUnitPrice = value.replace(/[^\d.]/g, '');
    },
    async fetchDictDataByAttribute() {
      const response = await this.$axios.get('manage/scmDictData/getDictData', {
        params: { dictType: 'product_attribute' }
      });
      this.productAttributes = response.data;
      this.productShow.productAttribute = this.dictCode;
    },
    async fetchDictDataByUnit() {
      const response = await this.$axios.get('manage/scmDictData/getDictData', {
        params: { dictType: 'product_unit' }
      });
      this.priductUnits = response.data;
      this.productShow.priductUnit = this.dictCode;
    },

    async handleProductAttributeChange(){
      console.log(this.productShow.productAttribute);
      const response = await this.$axios.get("manage/productCategory/selectProducts", {
        params: {dataType:this.productShow.productAttribute}
      });
      this.productTypes = response.data.productCategorys || [];
    },



    handleAvatarSuccess(res, file) {
      this.imageUrl=this.$basePath+"static/uploadImage/"+res.fileName;
      this.productShow.productImgsId=res.fileName;
    },
    //图片上传之前的验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }


  }
};
</script>
<style scoped>
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>